//
//  YSVideoCollectionCtrl.m
//  Yueshi
//
//  Created by yueshi－mac1 on 16/1/11.
//  Copyright © 2016年 悦食中国. All rights reserved.
//

#import "YSVideoCollectionCtrl.h"
#import "YSHomeDataTool.h"
#import "YSVideoCollectionCell.h"
#import "YSVideoCollectionEditCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YSMarkBottomBar.h"
#import "YSAdvert.h"
#import "YSHomeDataTool.h"
#import "YSVideoDetailsCtrl.h"

@interface YSVideoCollectionCtrl ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic)  UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *itemArray;
@property (assign, nonatomic) NSInteger pageIndex;
@property (assign, nonatomic) NSInteger currentMode;
@property (strong, nonatomic) YSMarkBottomBar *bottomBar;
@property (strong, nonatomic) NSMutableString *selectAdvertIds;//选中的id字符串，用逗号分隔
@property (strong, nonatomic) UILabel *nullPageLabel;
@property (assign, nonatomic) NSInteger deleteCount;
@end

@implementation YSVideoCollectionCtrl

- (NSMutableArray *)itemArray{
    if (!_itemArray) {
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}
   
- (void)viewDidLoad {
    [super viewDidLoad];
    _currentMode = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusChange:) name:kMarkStatusChangeNortif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemStatusChange:) name:kMarkVideoItemChangeNortif object:nil];
    
    [self initTableView];
    
    [self initBottomBar];
    
    NSString *nullTips =@"您还没有收藏的视频哦";
    _nullPageLabel = [UIUtil getPageTipLabelWithTipText:nullTips];
    [_nullPageLabel setHidden:YES];
    [self.view addSubview:_nullPageLabel];
    
}

- (void) initTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH - NavWithStatusBarH)];
    [self.tableView setBackgroundColor:PUBLIC_BG];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView registerNib:[UINib nibWithNibName:@"YSVideoCollectionCell" bundle:nil] forCellReuseIdentifier:@"YSVideoCollectionCell"];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.header = header;
    self.tableView.footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];
}

- (void) initBottomBar{
    __weak YSVideoCollectionCtrl *ctrl = self;
    YSMarkBottomBar *bottomBar = [YSMarkBottomBar new];
    bottomBar.userInteractionEnabled = YES;
    bottomBar.x = 0;
    bottomBar.y = SCREENH - NavWithStatusBarH - YSMarkBottomBarHeight;
    [bottomBar setHidden:YES];
    [self.view addSubview:bottomBar];
    
    //choose all
    [bottomBar setChooseOperation:^{
        if (self.bottomBar.statusBtn.selected) {
            //selected
            for (YSAdvert *advert in ctrl.itemArray) {
                advert.status = YES;
            }
        }else{
            for (YSAdvert *advert in ctrl.itemArray) {
                advert.status = NO;
            }
        }
        [self.tableView reloadData];
    }];
    
    [bottomBar setDeleteOperation:^{
        self.deleteCount = 0;
        ctrl.selectAdvertIds = [NSMutableString string];
        for (YSAdvert *advert in ctrl.itemArray) {
            if (advert.status) {
                [ctrl.selectAdvertIds appendString:[NSString stringWithFormat:@"%ld,",advert.advertId]];
                self.deleteCount++;
            }
        }
        
        NSString *ids = nil;
        if (ctrl.selectAdvertIds.length) {
            ids = [NSMutableString stringWithString: [ctrl.selectAdvertIds substringToIndex:ctrl.selectAdvertIds.length-1]];
        }
        [ctrl deleteMarkWithIds:ids];
    }];
    
    self.bottomBar = bottomBar;
}

- (void)checkRequestData{
    if (!_itemArray.count) {
        [self.tableView.header beginRefreshing];
    }else{
        [[NSNotificationCenter defaultCenter]postNotificationName:kSubPageMarkStatusChangeNortif object:[NSNumber numberWithInteger:showStatus]];
    }
}

- (void) requestData{
    if (ISLOGIN) {
        [YSHomeDataTool getMarkVideoListWithPageIndex:self.pageIndex success:^(YSAdvertRes *res) {
            [UIUtil refreshComplete:self.tableView];
            if (res.isSucc) {
                if (self.pageIndex == 0) {
                    [self.itemArray removeAllObjects];
                }
                [self.itemArray addObjectsFromArray:res.advertList];
                [self.tableView reloadData];
                
                if (!self.itemArray.count) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:kSubPageMarkStatusChangeNortif object:[NSNumber numberWithInteger:hideStatus]];
                    [_nullPageLabel setHidden:NO];
                    [self.bottomBar setHidden:YES];
                }else{
                    [[NSNotificationCenter defaultCenter] postNotificationName:kSubPageMarkStatusChangeNortif object:[NSNumber numberWithInteger:showStatus]];
                }
            }else{
                ShowTips(res.data);
            }
        } failure:^(NSError *e) {
            ShowTips(kRequestFailure);
        }];
    }else {
        [UIUtil refreshComplete:self.tableView];
        [_nullPageLabel setHidden:NO];
    }
}

- (void) statusChange:(NSNotification *)nortif{
    NSNumber *status = [nortif object];
    _currentMode = status.integerValue;
    
    if (status.integerValue == noEditStatusType) {
        if (self.itemArray.count) {
            for (YSAdvert *advert in _itemArray) {
                advert.status = NO;
            }
        }
        [_tableView registerNib:[UINib nibWithNibName:@"YSVideoCollectionCell" bundle:nil] forCellReuseIdentifier:@"YSVideoCollectionCell"];
        
        [self.bottomBar setHidden:YES];
        [self.tableView setHeight:SCREENH - NavWithStatusBarH];
    }else {
        if (!self.itemArray.count) {
            [self.bottomBar setHidden:YES];
        }else{
            [self.bottomBar setHidden:NO];
        }
        
        [_tableView registerNib:[UINib nibWithNibName:@"YSVideoCollectionEditCell" bundle:nil] forCellReuseIdentifier:@"YSVideoCollectionEditCell"];
        [self.tableView setHeight:SCREENH - NavWithStatusBarH - YSMarkBottomBarHeight];
    }
    
    [self.tableView reloadData];
}

- (void) itemStatusChange:(NSNotification *)nortif{
    for (YSAdvert *advert in _itemArray) {
        if (!advert.status) {
            self.bottomBar.statusBtn.selected = NO;
            break;
        }else{
            self.bottomBar.statusBtn.selected = YES;
        }
    }
    
    for (YSAdvert *advert in _itemArray) {
        if (advert.status) {
            self.bottomBar.deleteBtn.enabled = YES;
            break;
        }else{
            self.bottomBar.deleteBtn.enabled = NO;
        }
    }
    
    [self.tableView reloadData];
}

- (void) deleteMarkWithIds:(NSString *)ids{
    [YSHomeDataTool markVideoWithVideoId:ids type:2 success:^(BaseResponse *result) {
        if (result.isSucc) {
            if (self.deleteCount == self.itemArray.count) {
                [self.itemArray removeAllObjects];
            }
            [self requestData];
        }else {
            ShowTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

#pragma mark refresh action
- (void)headerRefresh{
    self.pageIndex = 0;
    [self requestData];
}

- (void)footerRefresh{
    self.pageIndex ++;
    [self requestData];
}

#pragma mark tableView delegate
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.currentMode == editStatusType) {
        YSVideoCollectionEditCell *cell = [YSVideoCollectionEditCell cellWithTableView:tableView];
        cell.advert = self.itemArray[indexPath.row];
        return cell;
    }else{
        YSVideoCollectionCell *cell = [YSVideoCollectionCell cellWithTableView:tableView];
        cell.advert = self.itemArray[indexPath.row];
        return cell;
    }
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_currentMode == editStatusType) {
        return [tableView fd_heightForCellWithIdentifier:@"YSVideoCollectionEditCell" cacheByIndexPath:indexPath configuration:^(YSVideoCollectionEditCell *cell) {
            [cell setAdvert:self.itemArray[indexPath.row]];
        }];
    }else{
        return [tableView fd_heightForCellWithIdentifier:@"YSVideoCollectionCell" cacheByIndexPath:indexPath configuration:^(YSVideoCollectionCell *cell) {
            [cell setAdvert:self.itemArray[indexPath.row]];
        }];
    }
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
    YSAdvert *advert = self.itemArray[indexPath.row];
    YSVideoDetailsCtrl *ctrl = [[YSVideoDetailsCtrl alloc] initWithAdvert:advert];
    
    [self.view.superview.viewController.navigationController pushViewController:ctrl animated:YES];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
